﻿using System.Net.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using System.Collections.Specialized;
using System.Net.Security;

namespace DingTalk.Common
{
    public static class HttpsHelper
    {
        /// <summary>
        /// Get请求发送
        /// </summary>
        /// <param name="requestUrl">url地址</param>
        /// <returns></returns>
        public static async Task<string> Get(string requestUrl, string token = "")
        {
            string responseBody = string.Empty;
            using (HttpClient httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Add("Method", "Get");
                httpClient.DefaultRequestHeaders.Add("KeepAlive", "false");
                httpClient.DefaultRequestHeaders.Add("UserAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

                if (!string.IsNullOrWhiteSpace(token))
                {
                    httpClient.DefaultRequestHeaders.Add("x-acs-dingtalk-access-token", token);
                }
                HttpResponseMessage response = await httpClient.GetAsync(requestUrl);
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
            }
            return responseBody;
        }
        /// <summary>
        /// post请求
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public static async Task<T> Post<T>(string Url, object message) where T : new()
        {
            var res = new T();
            string jsonContent = JsonConvert.SerializeObject(message);
            string responseBody = string.Empty;
            using (HttpClient httpClient = new HttpClient())
            {
                var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                httpClient.DefaultRequestHeaders.Add("Method", "Post");
                HttpResponseMessage response = await httpClient.PostAsync(Url, content);
                response.EnsureSuccessStatusCode();
                responseBody = await response.Content.ReadAsStringAsync();
                res = (T)JsonConvert.DeserializeObject<T>(responseBody);
            }
            return res;
        }

        public static dynamic Post(string url, string postData, string token)
        {
            //url = "https://api.dingtalk.com/v1.0/badge/codes/corpInstances";
            //token = "efac3ed1f19033bab476db1010aba771";

            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                request = WebRequest.Create(url) as HttpWebRequest;
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request.ProtocolVersion = HttpVersion.Version11;
                // 这里设置了协议类型。
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
                request.KeepAlive = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 100;
                ServicePointManager.Expect100Continue = false;
            }
            else
            {
                request = (HttpWebRequest)WebRequest.Create(url);
            }

            //SetHeaderValue(request.Headers, "x-acs-dingtalk-access-token", token);
            if (!string.IsNullOrWhiteSpace(token))
            {
                request.Headers.Add("x-acs-dingtalk-access-token", token);
            }
            request.Method = "POST";
            request.ContentType = "application/json";
            request.Referer = null;
            request.AllowAutoRedirect = true;
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.Accept = "*/*";

            byte[] data = Encoding.UTF8.GetBytes(postData);
            Stream newStream = request.GetRequestStream();
            newStream.Write(data, 0, data.Length);
            newStream.Close();

            //获取网页响应结果
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
            string result = string.Empty;
            using (StreamReader sr = new StreamReader(stream))
            {
                result = sr.ReadToEnd();
            }
            return result;
        }


        //public static dynamic PostPro(string url, string postData, string engineCode, string engineSecret)
        //{
        //    HttpWebRequest request = null;
        //    if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
        //    {
        //        request = WebRequest.Create(url) as HttpWebRequest;
        //        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
        //        request.ProtocolVersion = HttpVersion.Version11;
        //        // 这里设置了协议类型。
        //        ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;// SecurityProtocolType.Tls1.2; 
        //        request.KeepAlive = false;
        //        ServicePointManager.CheckCertificateRevocationList = true;
        //        ServicePointManager.DefaultConnectionLimit = 100;
        //        ServicePointManager.Expect100Continue = false;
        //    }
        //    else
        //    {
        //        request = (HttpWebRequest)WebRequest.Create(url);
        //    }

        //    request.Headers.Add("x-acs-dingtalk-access-token", token);
        //    request.Method = "POST";
        //    request.ContentType = "application/json";
        //    request.Referer = null;
        //    request.AllowAutoRedirect = true;
        //    request.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        //    request.Accept = "*/*";

        //    byte[] data = Encoding.UTF8.GetBytes(postData);
        //    Stream newStream = request.GetRequestStream();
        //    newStream.Write(data, 0, data.Length);
        //    newStream.Close();

        //    //获取网页响应结果
        //    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        //    Stream stream = response.GetResponseStream();
        //    //client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
        //    string result = string.Empty;
        //    using (StreamReader sr = new StreamReader(stream))
        //    {
        //        result = sr.ReadToEnd();
        //    }
        //    return result;
        //}
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }

        /// <summary>
        /// 指定Post地址使用Get 方式获取全部字符串
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string PostDic(string url, Dictionary<string, string> dic)
        {
            string result = string.Empty;
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";

            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion

            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }
    }

}
